package jp.co.tms.internal.runserver.test;

import java.io.IOException;
import java.net.BindException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import jp.co.tms.internal.runserver.IRunServerEventHandle;
import jp.co.tms.internal.runserver.RunServerCtrl;
import jp.co.tms.internal.runserver.exception.ConnectionIsInUseException;
import jp.co.tms.internal.runserver.exception.ConnectionIsOutException;
import jp.co.tms.internal.runserver.exception.NoHandleException;
import jp.co.tms.internal.runserver.exception.PortNumberIsUnLegalException;
import jp.co.tms.internal.task.IRunTask;
import jp.co.tms.internal.task.RunTask;

public class RunServerTester extends TimerTask implements IRunServerEventHandle{
	
	public final static int DEF_SECOND        = 1000;
	public final static int DEF_DELAY_TIME    = 4 * DEF_SECOND;
	public final static int DEF_INTERVAL_TIME = 1 * DEF_SECOND;
	
	private Timer _timer = new Timer();
	
	private RunServerCtrl _server = new RunServerCtrl(this);
	
	private int jobId = 0x0001;
	
	private Map<Integer, IRunTask> _map = new HashMap<Integer, IRunTask>();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new RunServerTester().start();
	}
	
	public RunServerTester(){
	}
	
	public void start(){
		try{
			//
			//
			_server.run();
			//
			//
			_timer.schedule(this, DEF_DELAY_TIME, DEF_INTERVAL_TIME);
		}
		catch (NoHandleException e){
			
		}
		catch (ConnectionIsInUseException e){
			
		}
		catch (PortNumberIsUnLegalException e){
			
		}
		catch (ConnectionIsOutException e){
			
		}
		catch (BindException e){
			
		}
		catch (IOException e){
			
		}
	}

	@Override
	public boolean onTaskFinish(int taskId) {
		IRunTask task = _map.get(taskId);
		if (task == null){
			return false;
		}
		
		System.out.println("TASK FINISHED : id = " + taskId + " | " + task.getCommand());
		
		_map.remove(taskId);
		
		return true;
	}

	@Override
	public boolean onTaskKilled(int taskId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTaskRunning(int taskId) {
		IRunTask task = _map.get(taskId);
		if (task == null){
			return false;
		}
		
		System.out.println("TASK RUNNING : id = " + taskId + " | " + task.getCommand());
		
		return true;
	}

	@Override
	public void run() {
		if (!_server.hasIdleCpu() ){
			return ;
		}
		
		IRunTask task = new RunTask(jobId, 0x1000, "ls -l");
		_map.put(jobId, task);
		
		jobId++;
		
		_server.startTask(task);
	}
}
